'use client';

import type { ISectionDetails } from '@/interfaces';
import { removeSection } from '@/services/api';
import { useMutation } from '@tanstack/react-query';
import { type FormEvent } from 'react';
import useToast from '@/hooks/useToast';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Link from 'next/link';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function DeleteSectionAdminPage({
  source,
  translatedFields,
}: {
  source: ISectionDetails;
  translatedFields: PrefixedTTranslatedFields<'sectionAdminPage'>;
}) {
  const { show } = useToast();

  const removeSectionMutation = useMutation(removeSection);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      show({
        type: 'PRIMARY',
        message: translatedFields.deletePage.wait,
      });

      const id = source.basic.id;
      await removeSectionMutation.mutateAsync({
        id,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.deletePage.deleteCompleted,
      });

      setTimeout(() => {
        show({
          type: 'SUCCESS',
          message: translatedFields.deletePage.refresh,
        });
      }, 1200);

      setTimeout(() => {
        location.replace('/admin/forum/section');
      }, 1500);
    } catch (e) {
      removeSectionMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <Box>
      <div className="card">
        <div className="card-body">
          <form
            onSubmit={onSubmit}
            className="vstack gap-4 align-items-center py-4"
          >
            <Link
              href={`/sections/${source.basic.id}`}
              className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
            >
              <span>
                {translatedFields.deletePage.deletePlaceholder1}&nbsp;
              </span>
              <span className="fw-semibold text-danger lead">{`⌈ ${source.basic.name} (ID. ${source.basic.id}) ⌋`}</span>
              <span>
                &nbsp;{translatedFields.deletePage.deletePlaceholder2}
              </span>
            </Link>
            <button
              type="submit"
              disabled={removeSectionMutation.isLoading}
              className="btn btn-danger col col-lg-2 mt-4"
            >
              {removeSectionMutation.isLoading && <Spinner classs="me-2" />}
              {translatedFields.deletePage.delete}
            </button>
          </form>
        </div>
      </div>
    </Box>
  );
}
